package com.chain.qs.common.web;

import com.chain.qs.common.utils.CacheUtils;
import com.google.common.collect.Maps;
import org.springframework.context.ApplicationListener;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.messaging.SessionConnectedEvent;
import java.util.HashMap;
import java.util.Map;

/**
 * ws新请求创建session 缓存
 */
@Component
public class WSSessionConnectedEvent implements ApplicationListener<SessionConnectedEvent> {

    @SuppressWarnings("unchecked")
    @Override
    public void onApplicationEvent(SessionConnectedEvent event) {
        StompHeaderAccessor headers = StompHeaderAccessor.wrap(event.getMessage()); //获取消息头
        String simpSessionId = (String)headers.getHeader("simpSessionId");
        Map<String, String> wsSessionMap = (Map<String, String>)CacheUtils.get("ws_sessions");
        wsSessionMap = (wsSessionMap == null ? Maps.newConcurrentMap() : wsSessionMap);
        wsSessionMap.put(simpSessionId, "");
        CacheUtils.put("ws_sessions", wsSessionMap);//将ws用户连接信息map格式放存放起来
    }
}
